import { reactive, ref } from 'vue'
import http from '@/http'
export interface registerForm {
  name: string,
  password: string,
  phone: string,
  phone_pre: string,
  country: string
  code:string // 邀请码
}
export interface loginForm {
  password: string,
  phone: string,
  phone_pre: string,
}
export interface adminLoginForm {
  code: string,
  name: string,
}

export interface changePwdForm {
  old_password: string,
  password: string,
  confirm_password: string
}

import type { FormRules, FormInstance } from 'element-plus'
export const login = () => {
  const ruleFormRef = ref<FormInstance>()
  const submitForm = async (formEl: FormInstance | undefined, callback: Function = () => { }) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        callback.apply(null)
      } else {
        console.log('error submit!', fields)
      }
    })
  }
  const rules = reactive<FormRules>({
    code: [{ required: true, message: 'Please input code', trigger: 'blur' }],
    name: [{ required: true, message: 'Please input username', trigger: 'blur' }],
  })

  const register = async (req: registerForm) => {
    return http.fetchPost('admin/register', req)
  }
  const userlogin = async (req: loginForm) => {
    return http.fetchGet('admin/login', req)
  }

  const userAdminlogin = async (req: adminLoginForm) => {
    return http.fetchGet('/login', req)
  }

  const changePwd = async (req: changePwdForm) => {
    return http.fetchPatch('admin/changePwd', req)
  }

  const form = ref({
    phone: '',
    password: '',
    phone_pre: ''
  })
  return {
    rules,
    form,
    ruleFormRef,
    submitForm,
    register,
    userlogin,
    changePwd,
    userAdminlogin
  }
}
